﻿using System.Collections.Generic;
using System.Linq;
using Missbot.Common;
using Missbot.Core.Base;
using Dolany.UtilityTool;
using JetBrains.Annotations;
using Missbot.AIModule.Base;
using Missbot.AIModule.OnlineStore;
using Missbot.Core.Cache;
using Missbot.Model.MsgInfos;

namespace Missbot.AIModule.Gaming.Gift
{
    [UsedImplicitly]
    public class GiftMod : IAIModule
    {
        public override string Name => "礼物";

        #region Svcs

        public GiftSvc GiftSvc { get; set; }
        public WaiterSvc WaiterSvc { get; set; }

        #endregion

        [ModuleEnter(Command = "兑换礼物", Description = "兑换指定的礼物", DailyLimit = 3, SyntaxHint = "[礼物名]")]
        public bool MakeGift(InboxSession session, string name)
        {
            var gift = GiftSvc[name];
            if (gift == null)
            {
                session.SendBack("未查找到该礼物！");
                return false;
            }

            var sellingGifts = GiftSvc.SellingGifts;
            if (sellingGifts.All(p => p.Name != name))
            {
                session.SendBack("该礼物未在礼物商店中出售，请使用 礼物商店 命令查看今日可兑换的礼物！");
                return false;
            }

            var itemRecord = ItemCollectionDA.Get(session.User.ID);
            var mdic = itemRecord.HonorCollections.SelectMany(p => p.Value.Items).ToDictionary(p => p.Key, p => p.Value);
            var osPerson = OSPersonDA.GetPerson(session.User.ID);
            if (!gift.Check(mdic, osPerson.Golds, out var msg))
            {
                session.SendBack($"兑换{name}需要：\n{msg}材料不足，无法兑换！");
                return false;
            }

            if (!WaiterSvc.WaitForConfirm(session, $"兑换{name}需要：\n{msg}是否兑换？"))
            {
                session.SendBack("操作取消！");
                return false;
            }

            itemRecord.ItemConsume(gift.MaterialDic);
            itemRecord.Update();
            osPerson.Golds -= gift.GoldNeed;
            osPerson.GiftIncome(name);
            osPerson.Update();

            session.SendBack("兑换成功！可以使用 赠送礼物 命令将礼物送给其他人！");

            return true;
        }

        [ModuleEnter(Command = "我的礼物", Description = "查看自己拥有的礼物")]
        public bool MyGifts(InboxSession session)
        {
            var osPerson = OSPersonDA.GetPerson(session.User.ID);
            if (osPerson.GiftDic.IsNullOrEmpty())
            {
                session.SendBack("你当前没有任何礼物！");
                return false;
            }

            var msg = string.Join(",", osPerson.GiftDic.Select(p => $"{p.Key}*{p.Value}"));
            session.SendBack($"你当前持有的礼物：\n{msg}");

            return true;
        }

        [ModuleEnter(Command = "礼物商店", Description = "浏览礼物商店，查看今日可兑换的礼物")]
        public bool GiftShop(InboxSession session)
        {
            var sellingGifts = GiftSvc.SellingGifts;
            var buffer = new OutputBuffer(session);
            buffer.Add("当前可兑换的礼物有(礼物名/羁绊值/魅力值)：");
            foreach (var gift in sellingGifts)
            {
                buffer.Add($"{gift.Name}/{gift.Intimate}/{gift.Glamour}");
            }

            buffer.Add("可以使用 【查看礼物 [礼物名]】 命令来查看详细信息；或者使用 【兑换礼物 [礼物名]】 命令来兑换指定礼物");
            buffer.Send();
            return true;
        }

        [ModuleEnter(Command = "查看礼物", Description = "查看礼物的详细信息", SyntaxHint = "[礼物名]")]
        public bool ViewGift(InboxSession session, string name)
        {
            var gift = GiftSvc[name];
            if (gift == null)
            {
                session.SendBack("未查找到该礼物！");
                return false;
            }

            var buffer = new OutputBuffer(session);
            buffer.AddPair(new Dictionary<string, string>
            {
                ["礼物名"] = gift.Name,
                ["描述"] = gift.Description,
                ["羁绊值"] = gift.Intimate.ToString(),
                ["魅力值"] = gift.Glamour.ToString(),
                ["兑换需要材料"] = string.Join(", ", gift.MaterialDic.Select(p => $"{p.Key}*{p.Value}")),
                ["兑换需要金币"] = gift.GoldNeed.CurencyFormat()
            });
            buffer.Send();
            return true;
        }

        [ModuleEnter(Command = "查看羁绊", Description = "查看和指定成员的羁绊值", SyntaxHint = "[@用户名]")]
        public bool ViewRelationship(InboxSession session, InstanceUser aimUser)
        {
            if (aimUser.ID == session.User.ID)
            {
                session.SendBack("和自己的羁绊，永远是0！");
                return false;
            }

            var relationship = IntimateRelationshipDA.GetSumIntimate(session.Group.ID, session.User.ID, aimUser.ID);
            session.SendBack($"你们之间的羁绊值是：{relationship} ！");

            return true;
        }

        [ModuleEnter(Command = "赠送礼物", Description = "赠送某个成员一个礼物", SyntaxHint = "[@用户名] [礼物名]")]
        public bool PresentGift(InboxSession session, InstanceUser aimUser, string name)
        {
            if (aimUser.ID == session.User.ID)
            {
                session.SendBack("你居然给自己送礼物！");
                return false;
            }

            var osPerson = OSPersonDA.GetPerson(session.User.ID);
            if (osPerson.GiftDic == null || !osPerson.GiftDic.ContainsKey(name))
            {
                session.SendBack("你没有这个礼物！");
                return false;
            }

            osPerson.GiftDic[name]--;
            osPerson.Update();

            var glamourRecord = GlamourRecordDA.Get(session.Group.ID, aimUser.ID);
            var gift = GiftSvc[name];
            glamourRecord.Glamour += gift.Glamour;
            glamourRecord.Update();

            var relationship = new IntimateRelationshipRecord
            {
                GroupID = session.Group.ID,
                UserPair = new[] { session.User.ID, aimUser.ID },
                Value = gift.Intimate,
                Name = gift.Name
            };
            relationship.Insert();

            var msg = $"赠送成功！{aimUser.Name}增加了 {gift.Glamour} 点魅力值，你们之间的羁绊值增加了 {gift.Intimate} 点！";
            session.SendGroup(aimUser, msg);

            return true;
        }
    }
}